@{
	Layout = null;
}

<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
	<form class="layui-form" style="margin: 20px;">
		@Html.AntiForgeryToken()
		<input type="hidden" id="roleId" name="id" />
		<div class="layui-form-item">
			<label class="layui-form-label">角色名</label>
			<div class="layui-input-block">
				<input type="text" id="roleName" name="roleName" required lay-verify="required" placeholder="请输入角色名" autocomplete="off" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">状态</label>
			<div class="layui-input-block">
				<input type="radio" name="roleStatus" value="1" title="启用" checked>
				<input type="radio" name="roleStatus" value="0" title="禁用">
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-input-block">
				<button class="layui-btn" lay-submit lay-filter="updateRole">立即提交</button>
				<button type="reset" class="layui-btn layui-btn-primary">重置</button>
			</div>
		</div>
	</form>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
	layui.use(['form', 'layer'], function(){
		var form = layui.form;
		var layer = layui.layer;

		// Get role ID from URL query parameter
		var urlParams = new URLSearchParams(window.location.search);
		var roleId = urlParams.get('id');

		if (roleId) {
			// Fetch role data and populate the form
			$.ajax({
				url: '/Role/GetRoleById?id=' + roleId,
				type: 'GET',
				dataType: 'json',
				success: function(res) {
					if (res) {
						$('#roleId').val(res.id);
						$('#roleName').val(res.roleName);
						$('input[name="roleStatus"][value="' + res.roleStatus + '"]').prop('checked', true);
						form.render(); // Re-render form elements after setting values
					}
				},
				error: function(xhr, status, error) {
					layer.msg('获取角色数据失败', { icon: 2 });
					console.error('Error fetching role data:', xhr.responseText);
				}
			});
		}

		// Listen for form submission
		form.on('submit(updateRole)', function(data){
			var token = $('input[name="__RequestVerificationToken"]').val();
			$.ajax({
				url: '/Role/UpdateRole',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				headers: {
					'RequestVerificationToken': token
				},
				data: JSON.stringify(data.field),
				success: function(res){
					if(res === 1){
						layer.msg('修改成功', {icon: 1});
						parent.layer.close(parent.layer.getFrameIndex(window.name)); // Close the modal
						parent.show(); // Refresh parent table
					} else {
						layer.msg('修改失败', {icon: 2});
					}
				},
				error: function(xhr, status, error){
					layer.msg('修改失败: ' + (xhr.responseText || '服务器错误'), {icon: 2});
					console.error('Error updating role:', xhr.responseText);
				}
			});
			return false; // Prevent default form submission
		});
	});
</script> 